package com.zdkj.subway.check.util;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class DateFormat {

    public static String ex_strDate_to_date(String dateStr,String toFormat) throws ParseException {

        if(dateStr.matches("\\d+\\-\\d+\\-\\d+")){
            SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd");
            Date parse = s.parse(dateStr);
            SimpleDateFormat s_to=new SimpleDateFormat(toFormat);
            return s_to.format(parse);
        }

        if(dateStr.matches("\\d+\\-\\d+\\-\\d+\\s+\\d+:\\d+:\\d+")){
            SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parse = s.parse(dateStr);
            SimpleDateFormat s_to=new SimpleDateFormat(toFormat);
            return s_to.format(parse);
        }
        return dateStr;
    }

    public static Date panDuanDate(Object timeStr) throws ParseException {
        String time=timeStr+"";
        if(StringUtils.isEmpty(time)){
            return null;
        }
        String format="";
        if(time.matches("\\d+\\-\\d+\\-\\d+\\s+\\d+:\\d+:\\d+")){
            format="yyyy-MM-dd HH:mm:ss";
        }else if(time.matches("\\d+\\-\\d+\\-\\d+")){
            format="yyyy-MM-dd";
        }else if(time.matches("\\d{8}")){
            format="yyyyMMdd";
        }
        SimpleDateFormat s=new SimpleDateFormat(format);
        Date parse = s.parse(time);
        return parse;
    }

    public static String date_ex_str(Date timeStr) throws ParseException {
        SimpleDateFormat sm=new SimpleDateFormat("yyyy-MM-dd");
        return sm.format(timeStr);
    }

    public static String date_ex_str(Date timeStr,String format) throws ParseException {
        SimpleDateFormat sm=new SimpleDateFormat(format);
        return sm.format(timeStr);
    }

    /**
     *
     * @param timeStr
     * @param days
     * @return
     * @throws ParseException
     */
    public static Date date_add_or_sub_days(Date timeStr,int days) throws ParseException {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(timeStr);
        calendar.add(calendar.DATE,days); //把日期往后增加一天,整数  往后推,负数往前移动
        timeStr=calendar.getTime();
        return timeStr;
    }

    /**
     * 增加秒
     * @param timeStr
     * @param seconds
     * @return
     * @throws ParseException
     */
    public static Date date_add_or_sub_seconds(Date timeStr,int seconds) throws ParseException {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(timeStr);
        calendar.add(calendar.SECOND,seconds); //把日期往后增加几秒,整数  往后推,负数往前移动
        timeStr=calendar.getTime();
        return timeStr;
    }

    /**
     * Date转LocalDate
     * @param date
     */
    public static LocalDate dateTOLocalDate(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        // atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
        return instant.atZone(zoneId).toLocalDate();
    }

    public static Date LocalDateToUdate(LocalDate localDate) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
        java.util.Date date = Date.from(instant);
        return date;
    }
    public static Date stringToDateFormat(String date){
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        try {
            return dateFormat.parse(date);
        } catch (ParseException e) {
            return null;
        }
    }
    /**
     * 把日期格式化为字符串
     * @param date
     *          日期
     * @return
     *          返回格式化之后的字符串
     */
    public static Date stringToDate(String date) throws  ParseException{
        String format = "yyyy-MM-dd";
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.parse(date);
    }

    //获取localdata
    public static LocalDate getLocalDate(java.util.Date date) {
        //将参数转为系统默认的格式
        java.util.Date date1 = new Date(date.getTime());
        Instant instant = date1.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        LocalDate localDate = localDateTime.toLocalDate();
        return localDate;
    }
    /**
     * 时间戳转date
     * @return
     */
    public static Date timeToDate (Long time) {
        //时间戳转化为Sting或Date
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String d = format.format(time);
        Date date= null;
        try {
            date = format.parse(d);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * LocalDate转String
     * @return
     */
    public static String LocalDateTurnString(LocalDate localDate) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dateStr = localDate.format(fmt);
        return dateStr;
    }

    public static String formatDateByRecordTime(Date date,String format) {
        // 创建日期格式化对象，指定格式为yyyyMMdd
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat sdf = new SimpleDateFormat(format);
        // 格式化日期并返回结果
        return sdf.format(date);
    }
    /**
     * date转LocalDate
     * @return
     */
    public static LocalDate DateTurnLocalDate(Date date){
        Instant instant =  date.toInstant();
        LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        LocalDate ld = ldt.toLocalDate();
        return ld;
    }

    /**
     * date转LocalDateTime
     * @return
     */
    public static LocalDateTime DateTurnLocalDateTime(Date date){
        Instant instant =  date.toInstant();
        LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        return ldt;
    }

    /**
     * 	String 类型转为 LocalDate类型
     *
     */
    public static LocalDate StringTurnLocalDate(String date) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date2 = LocalDate.parse(date, fmt);
        return date2;
    }

    /**
     * 	String 类型转为 LocalDateTime 类型
     *
     */
    public static LocalDateTime StringTurnLocalDateTime(String date) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime LocalTime = LocalDateTime.parse(date,fmt);
        return LocalTime;
    }
    /**
     * 当前日期
     * 	LocalDateTime 类型转为 String 类型
     *
     */
    public static String currLocalDateTimeTurnString() {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.now();
        String dateStr = localDateTime.format(fmt);
        return dateStr;
    }

    /**
     * BOM编号/售票员工号排序
     * @param bom
     * @return
     */
    public static String bomOrJobNoSort(String bom){
        String[] split = bom.split(",");
        Arrays.sort(split);
        //排序后
        String bomOrJobNoSort = StringUtils.join(split, ",");
        return bomOrJobNoSort;
    }

    /**
     * 根据开始时间和结束时间返回时间段内的时间集合
     *
     * @param beginDate
     * @param endDate
     * @return List
     * @throws ParseException
     */
    public static List<String> getDatesBetweenTwoDate(String beginDate, String  endDate) throws ParseException {

        //格式转换
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> lDate = new ArrayList<>();
        lDate.add(beginDate);// 把开始时间加入集合
        if(beginDate.equals(endDate)){
            return lDate;
        }
        Calendar cal = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        cal.setTime(sdf.parse(beginDate));
        boolean bContinue = true;
        while (bContinue) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            cal.add(Calendar.DAY_OF_MONTH, 1);
            // 测试此日期是否在指定日期之后
            if (sdf.parse(endDate).after(cal.getTime())) {
                lDate.add(sdf.format(cal.getTime()));
            } else {
                break;
            }
        }
        // 把结束时间加入集合
        lDate.add(endDate);
        return lDate;

    }


    /**
     * 根据传入时间获取对应月份总天数
     * @param date
     * @return
     */
    public static int dayByMonth(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH)+1;
        switch (month) {
            case 1: case 3: case 5:case 7:  case 8:  case 10:  case 12:
                return 31;
            case 4:  case 6: case 9:  case 11:
                return 30;
            //对于2月份需要判断是否为闰年
            case 2:
                if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                    return 29;
                } else {
                    return 28;
                }
            default:
                return 0;
        }
    }

    /**
     * 根据传入时间获取对应月份最后一天日期LastDay
     * @param date
     * @return
     */
    public static Date getLastDayOfMonth(final Date date) {
        final Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        final int last = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        cal.set(Calendar.DAY_OF_MONTH, last);
        return cal.getTime();
    }

    /**
     * 检验日期格式是否正确
     * @param dttm
     * @param
     * @return
     */
    public static boolean isDate(String dttm, String format) {
        if (dttm == null || dttm.isEmpty() || format == null || format.isEmpty()) {
            return false;
        }

        if (format.replaceAll("'.+?'", "").indexOf("y") < 0) {
            format += "/yyyy";
            java.text.DateFormat formatter = new SimpleDateFormat("/yyyy");
            dttm += formatter.format(new Date());
        }

        java.text.DateFormat formatter = new SimpleDateFormat(format);
        formatter.setLenient(false);
        ParsePosition pos = new ParsePosition(0);
        Date date = formatter.parse(dttm, pos);

        if (date == null || pos.getErrorIndex() > 0) {
            return false;
        }
        if (pos.getIndex() != dttm.length()) {
            return false;
        }

        if (formatter.getCalendar().get(Calendar.YEAR) > 9999) {
            return false;
        }

        return true;
    }
}
